package cn.tianya.irock.freemarker.core;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import cn.tianya.irock.bll.SiteManager;
import cn.tianya.irock.data.model.Site;
import cn.tianya.irock.data.model.Template;
import cn.tianya.irock.exceptions.ApplicationException;

import freemarker.cache.TemplateLoader;

public class PageTemplateLoader implements TemplateLoader {
	
	public void closeTemplateSource(Object templateSource) throws IOException {
	}

	public Object findTemplateSource(String name) throws IOException {
		Site site = null;
		Template template = null;
		String[] pm = null;
		
		site = SiteManager.getCurrentSite();
		name = name.replace("_", "");
		pm = name.split("\\.");
		try {
			if (pm.length == 2) {
				template = (Template)SiteManager.getTemplate(site, pm[0], pm[1]);
			} else {
				template = (Template)SiteManager.getTemplate(site, pm[1], pm[2]);
			}
			
		} catch (ApplicationException ex) {
		}
		return template == null ? null : template.getContent();
	}

	public long getLastModified(Object templateSource) {
		return -1l;
	}

	public Reader getReader(Object templateSource, String encoding) throws IOException {
		return new StringReader((String) templateSource);
	}

}
